<template>
  <div class="login-container">
    <div class="card">
      <h2>跑腿员登录</h2>
      
      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <button 
          class="tab-btn" 
          :class="{ active: loginType === 'account' }"
          @click="loginType = 'account'"
        >
          账号密码登录
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: loginType === 'phone' }"
          @click="loginType = 'phone'"
        >
          手机号码登录
        </button>
      </div>
      
      <form @submit.prevent="handleLogin">
        <!-- 账号登录方式 -->
        <div v-if="loginType === 'account'">
          <!-- 用户名 -->
          <div class="form-group">
            <label>用户名</label>
            <input 
              type="text" 
              v-model="form.runner_account" 
              required
              placeholder="请输入用户名"
            >
          </div>
        </div>
        
        <!-- 手机登录方式 -->
        <div v-if="loginType === 'phone'">
          <div class="form-group">
            <label>手机号码</label>
            <input 
              type="tel" 
              v-model="form.phone" 
              required
              placeholder="请输入手机号码"
              pattern="1[3-9]\d{9}"
            >
          </div>
          
          <div class="form-group code-group">
            <div>
              <label>验证码</label>
              <input 
                type="text" 
                v-model="form.code" 
                required
                placeholder="请输入验证码"
              >
            </div>
            <button 
              type="button" 
              class="get-code-btn"
              :disabled="countdown > 0"
              @click="getVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </button>
          </div>
        </div>
        
        <!-- 密码（仅账号登录显示） -->
        <div class="form-group" v-if="loginType === 'account'">
          <label>密码</label>
          <input 
            type="password" 
            v-model="form.runner_password" 
            required
            placeholder="请输入密码"
          >
        </div>
        
        <!-- 记住我选项 -->
        <div class="remember-me">
          <label class="checkbox-label">
            <input 
              type="checkbox" 
              v-model="rememberMe"
            >
            记住我
          </label>
        </div>

        <button type="submit" class="submit-btn">登录</button>
        <p class="link-text">
          没有账号？<router-link to="/register">去注册</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<style scoped>
/* 核心：外层容器 Flex 布局，实现水平+垂直居中 */
.login-container {
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

/* 内部卡片样式 */
.card {
  width: 350px;
  padding: 2.5rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

/* 登录方式切换标签 */
.login-tabs {
  display: flex;
  margin-bottom: 1.5rem;
  border-bottom: 1px solid #eee;
}

.tab-btn {
  flex: 1;
  padding: 0.5rem 0;
  background: none;
  border: none;
  font-size: 0.95rem;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab-btn.active {
  color: #3B82F6;
  font-weight: 500;
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #3B82F6;
}

/* 表单内部样式 */
.form-group {
  margin-bottom: 1.5rem;
}

/* 验证码和按钮组合样式 */
.code-group {
  display: flex;
  gap: 0.5rem;
}

.code-group > div {
  flex: 1;
}

.get-code-btn {
  width: 100px;
  height: 42px;
  margin-top: 1.7rem;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  color: #666;
  cursor: pointer;
  font-size: 0.85rem;
}

.get-code-btn:disabled {
  background-color: #eee;
  color: #aaa;
  cursor: not-allowed;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
  font-size: 0.9rem;
}

.form-group input {
  width: 95%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

/* 记住我选项 */
.remember-me {
  margin-bottom: 1.5rem;
  text-align: left;
}

.checkbox-label {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 0.9rem;
  cursor: pointer;
}

.checkbox-label input {
  width: auto;
  margin-right: 0.5rem;
}

.submit-btn {
  width: 100%;
  padding: 0.9rem;
  background-color: #3B82F6;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #2563EB;
}

.link-text {
  text-align: center;
  margin-top: 1.2rem;
  font-size: 0.9rem;
}

.link-text a {
  color: #3B82F6;
  text-decoration: none;
}
</style>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const loginType = ref('account') // 'account' 或 'phone'
const rememberMe = ref(false)
const countdown = ref(0)

const form = ref({
  runner_account: '',
  runner_password: '',
  phone: '',
  code: ''
})

// 页面加载时检查是否有记住的登录信息
onMounted(() => {
  const savedAccount = localStorage.getItem('savedAccount')
  if (savedAccount) {
    const accountData = JSON.parse(savedAccount)
    form.value.runner_account = accountData.account
    form.value.runner_password = accountData.password
    rememberMe.value = true
  }
})

// 获取验证码
const getVerificationCode = async () => {
  if (!form.value.phone || !/^1[3-9]\d{9}$/.test(form.value.phone)) {
    alert('请输入有效的手机号码')
    return
  }
  
  try {
    // 调用后端获取验证码接口
    await request.post('/runner/send-code', { phone: form.value.phone })
    alert('验证码已发送，请注意查收')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('获取验证码失败', error)
    alert('获取验证码失败，请稍后重试')
  }
}

// 处理登录
const handleLogin = async () => {
  try {
    let res
    if (loginType.value === 'account') {
      // 账号密码登录
      res = await request.post('/runner/login', {
        runner_account: form.value.runner_account,
        runner_password: form.value.runner_password
      })
      
      // 如果勾选了记住我，保存账号密码
      if (rememberMe.value) {
        localStorage.setItem('savedAccount', JSON.stringify({
          account: form.value.runnerAccount,
          password: form.value.runnerPassword
        }))
      } else {
        // 否则清除保存的账号信息
        localStorage.removeItem('savedAccount')
      }
    } else {
      // 手机验证码登录
      res = await request.post('/runner/login-by-phone', {
        phone: form.value.phone,
        code: form.value.code
      })
    }
    
    // 存储token和用户信息
    localStorage.setItem('token', res.token)
    localStorage.setItem('user', JSON.stringify(res.user))
    
    // 检查审核状态
    if (res.data.auditStatus !== 1) {
      alert('账号未通过审核或待审核')
      return
    }
    
    router.push('/dashboard') // 跳转到工作台
  } catch (error) {
    console.error('登录失败', error)
    alert(error.message || '登录失败，请检查您的登录信息')
  }
}
</script>
    